package 华为OD机试B卷复用题.进阶题;

import utils.MyUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class HJ14_服务失效判断 {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner in = new Scanner(new File("src/main/java/华为OD机试B卷复用题/进阶题/input/14.txt"));
        MyUtil.START();
        Solution(in);
        MyUtil.END();
    }

    static void Solution(Scanner in) {
        String[] sArray = in.nextLine().split(",");
        int len = sArray.length;
        List<String> services = new ArrayList<>();
        // 入度
        Map<String, Integer> inDegree = new HashMap<>();
        // 存储边，类似邻接表，因为不是纯数字 所以不好用邻接矩阵
        Map<String, List<String>> edges = new HashMap<>();
        for (int i = 0; i < len; i++) {
            String[] tmp = sArray[i].split("-");
            inDegree.put(tmp[0], inDegree.getOrDefault(tmp[0], 0) + 1);
            services.add(tmp[0]);
            services.add(tmp[1]);
            List<String> edgeFromThisPoint =
                    edges.getOrDefault(tmp[1], new ArrayList<>()); // 取出该点对应边集
            edgeFromThisPoint.add(tmp[0]); // 边集中加入新边
            edges.put(tmp[1], edgeFromThisPoint);
        }
        // 处理故障服务
        String[] guzhang = in.nextLine().split(",");
        Map<String, Integer> oldInDgree = new HashMap<>(inDegree);
        for (int i = 0; i < guzhang.length; i++) {
            String now = guzhang[i];
            inDegree.put(now, -1); // 故障服务直接设入度为-1
            List<String> edgeFromThisPoint = edges.getOrDefault(now, new ArrayList<>());
            for (int j = 0; j < edgeFromThisPoint.size(); j++) {
                String to = edgeFromThisPoint.get(j);
                inDegree.put(to, inDegree.getOrDefault(to, 0) - 1); // 去掉故障服务后 剩下点的入度更新
            }
        }
        // 保存已访问过的顶点
        Map<String, Boolean> isVisited = new HashMap<>();
        List<String> result = new ArrayList<>();
        for (int i = 0; i < services.size(); i++) {
            String s = services.get(i);
            if (!isVisited.getOrDefault(s, false)) {
                isVisited.put(s, true);
                if (inDegree.getOrDefault(s, 0) == oldInDgree.getOrDefault(s, 0)) {
                    result.add(s);
                }
            }
        }
        if (result.size() == 0) {
            System.out.print(",");
        } else {
            for (int i = 0; i < result.size(); i++) {
                if (i != 0) {
                    System.out.print(",");
                }
                System.out.print(result.get(i));
            }
        }
    }
}
